<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="12">
          <a-form-item label="名称" v-bind="validateInfos.name">
            <a-input v-model:value="formData.name" placeholder="请输入服务公司名称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="税号" v-bind="validateInfos.businessLicenseNo">
            <a-input v-model:value="formData.businessLicenseNo" placeholder="请输入营业执照编号（税号）" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="法人姓名" v-bind="validateInfos.legalName">
            <a-input v-model:value="formData.legalName" placeholder="请输入法人姓名" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="法人身份证号" v-bind="validateInfos.legalCard">
            <a-input v-model:value="formData.legalCard" placeholder="请输入法人身份证号码" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="法人身份证正面" v-bind="validateInfos.legalSfzZm">
	          <j-image-upload :fileMax=1 bizPath="company/sfz" v-model:value="formData.legalSfzZm" :disabled="disabled"></j-image-upload>
            <span style="color: red;">支持jpg/png文件，大小不超过2M</span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="法人身份证反面" v-bind="validateInfos.legalSfzFm">
	          <j-image-upload :fileMax=1 bizPath="company/sfz" v-model:value="formData.legalSfzFm" :disabled="disabled"></j-image-upload>
            <span style="color: red;">支持jpg/png文件，大小不超过2M</span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="营业执照" v-bind="validateInfos.businessLicensePhoto">
            <j-image-upload :fileMax=1 bizPath="company/yyzz" v-model:value="formData.businessLicensePhoto" :disabled="disabled"></j-image-upload>
            <span style="color: red;">支持jpg/png文件，大小不超过2M</span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="合同文件" v-bind="validateInfos.contractFile">
            <j-upload :maxCount=5 bizPath="company/htwj" fileType="file" fileFormat="jpg,png,pdf,doc,docx" v-model:value="formData.contractFile" :disabled="disabled" ></j-upload>
            <span style="color: red;">支持jpg/png/pdf/doc/docx文件，最多5张，每张大小不超过5M</span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="开户名" v-bind="validateInfos.bankAccount">
            <a-input v-model:value="formData.bankAccount" placeholder="请输入开户名" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="开户号" v-bind="validateInfos.bankCard">
            <a-input v-model:value="formData.bankCard" placeholder="请输入开户号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="开户行" v-bind="validateInfos.bankCode">
            <j-category-select placeholder="请选择开户行" v-model:value="formData.bankCode"
                               pcode="A03" :back="true" :isCode="true" @change="handleBankNameChange"/>
          </a-form-item>
        </a-col>
        <a-col :lg="12">
          <a-form-item label="开户分行" v-bind="validateInfos.branchCode">
<!--            <j-dict-select-tag placeholder="请选择开户分行" v-model:value="formData.branchCode"
                               dictCode="tb_config,name,value,pid='1642813769826070529'" :disabled="disabled"
                                @change="handleChangeBranch"/>-->

            <a-select
              v-model:value="formData.branchCode"
              show-search
              allow-clear
              labelInValue
              :fieldNames="fieldNames"
              placeholder="请选择开户分行"
              :options="branchOptions"
              @change="handleChangeBranch"
            ></a-select>

          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系人姓名" v-bind="validateInfos.contactName">
            <a-input v-model:value="formData.contactName" placeholder="请输入联系人姓名" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系人电话" v-bind="validateInfos.contactPhone">
            <a-input v-model:value="formData.contactPhone" placeholder="请输入联系人电话" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系人邮箱" v-bind="validateInfos.contactEmail">
            <a-input v-model:value="formData.contactEmail" placeholder="请输入联系人邮箱" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
import {computed, defineExpose, defineProps, nextTick, reactive, ref} from 'vue';
import {useMessage} from '/@/hooks/web/useMessage';
import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
import JUpload from "/@/components/Form/src/jeecg/components/JUpload/JUpload.vue";
import JCategorySelect from '/@/components/Form/src/jeecg/components/JCategorySelect.vue';
import JDictSelectTag from "/@/components/Form/src/jeecg/components/JDictSelectTag.vue";
import {getValueType} from '/@/utils';
import {queryBranchByBankCode,saveOrUpdate} from '../CaishuiServiceCompany.api';
import {Form} from 'ant-design-vue';
import type { SelectProps } from 'ant-design-vue';

const branchOptions = ref<SelectProps['options']>([]);
const fieldNames = {
  value: 'value',
  label: 'name',
};

const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    name: '',   
    businessLicenseNo: '',   
    businessLicensePhoto: '',   
    legalName: '',   
    legalCard: '',   
    legalSfzZm: '',   
    legalSfzFm: '',   
    contactName: '',   
    contactPhone: '',   
    contactEmail: '',   
    bankName: '招商银行',
    bankAccount: '',   
    bankCard: '',
    bankCode: 'A03A01',
    branchName: '',
    branchCode: undefined,
    contractFile: '',
    status: undefined,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 6 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    name: [{ required: true, message: '请输入服务公司名称!'},],
    businessLicenseNo: [{ required: true, message: '请输入营业执照编号（税号）!'},],
    legalName: [{ required: true, message: '请输入法人姓名!'},],
    legalCard: [{ required: true, message: '请输入法人身份证号码!'},],
    legalSfzZm: [{ required: true, message: '请上传法人身份证正面照!'},],
    legalSfzFm: [{ required: true, message: '请上传法人身份证反面照!'},],
    businessLicensePhoto: [{ required: true, message: '请上传营业执照!'},],
    contractFile: [{ required: true, message: '请上传合同文件!'},],
    contactName: [{ required: true, message: '请输入联系人姓名!'},],
    contactPhone: [{ required: true, message: '请输入联系人电话!'},],
    contactEmail: [{ required: true, message: '请输入联系人邮箱!'},],
    bankCode: [{ required: true, message: '请选择开户行!'},],
    branchCode: [{ required: true, message: '请选择开户分行!'},],
    bankAccount: [{ required: true, message: '请输入开户名!'},],
    bankCard: [{ required: true, message: '请输入开户号!'},],
  };
  const { resetFields, validate, validateInfos, clearValidate } = useForm(formData, validatorRules, { immediate: true });

   // 表单禁用
   const disabled = computed(()=>{
      let bool = false;
      if(props.formBpm === true){
        if(props.formData.disabled === false){
          bool = false;
        }else{
          bool =  true;
        }
      }
      bool = props.formDisabled;
      if(bool){
        //清除表单验证
        clearValidate();
      }
      return bool;
   });

  /**
   * 根据开户行编码查询开户行分行
   * @param bankCode
   */
  function getBranchByBankCode(bankCode){
     queryBranchByBankCode({bankCode: bankCode}).then((res) => {
       if (res.success) {
         branchOptions.value = res.result;
       }
     });
   }

  /**
   * 开户行改变事件
   * @param e
   */
  function handleBankNameChange(value,obj){
    formData.bankCode = obj.code;
    formData.bankName = obj.title;
    getBranchByBankCode(formData.bankCode);
  }

  /**
   * 改变开户分行事件
   * @param e
   */
  function handleChangeBranch(e){
    formData.branchName = e.label;
    formData.branchCode = e.value;
  }

  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, record);
      if(formData.bankCode) {
        getBranchByBankCode(formData.bankCode);
      }
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //数据格式化
    let model = formData;
    if (model.id) {//编辑
       isUpdate.value = true;
       model.updateBy = "";
       model.updateTime = "";
    }else {//新增
       model.createBy = "";
       model.createTime = "";
       model.sysOrgCode = "";
       model.updateBy = "";
       model.updateTime = "";
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
</style>
